package iotwisp.school.api.controller.pc_admin.system;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import iotwisp.base.cqrs.BusinessException;
import iotwisp.base.orm.query.pagination.Pagination;
import iotwisp.base.rest.JSONResultDTO;
import iotwisp.base.rest.RestBaseController;
import iotwisp.base.util.JSONUtils;
import iotwisp.base.util.UUIDGenerator;
import iotwisp.school.config.IotWispSchoolConfig;
import iotwisp.school.system.command.CreateImageSCmd;
import iotwisp.school.system.entity.Image;
import iotwisp.school.system.qo.ImageQO;
import iotwisp.school.system.service.ImageService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/system/image")
public class ImageController extends RestBaseController {

	@Autowired
	private IotWispSchoolConfig iotWispSchoolConfig;
	@Autowired
	private ImageService imageService;

	@GetMapping("/query")
	public ResponseEntity<JSONResultDTO> queryRole(@RequestParam(name = "qo") String qoJson)
			throws UnsupportedEncodingException {

		ImageQO qo = JSONUtils.parseObject(URLDecoder.decode(qoJson, "UTF-8"), ImageQO.class);

		switch (qo.getResultType()) {
		case ImageQO.RESULT_TYPE_COUNT:
			Integer count = imageService.queryCount(qo);
			return ResponseEntity.ok(createSuccessResult(count));
		case ImageQO.RESULT_TYPE_UNIQUE:
			Image image = imageService.queryUnique(qo);
			return ResponseEntity.ok(createSuccessResult(image));
		case ImageQO.RESULT_TYPE_LIST:
			List<Image> images = imageService.queryList(qo);
			return ResponseEntity.ok(createSuccessResult(images));
		case ImageQO.RESULT_TYPE_PAGINATION:
			Pagination pagination = imageService.queryPagination(qo);
			return ResponseEntity.ok(createSuccessResult(pagination));
		default:
			return ResponseEntity.badRequest()
					.body(createFailResult(BusinessException.NECESSARY_PARAM_NULL, "resultType值有误", null));
		}

	}

	@PostMapping("/upload")
	public ResponseEntity<JSONResultDTO> uploadImage(@RequestParam("file") MultipartFile file,
			@RequestParam String useType) {

		if (file.isEmpty()) {
			return ResponseEntity.badRequest().body(createFailResult("no_file", "没有图片", null));
		}

		String path = iotWispSchoolConfig.getFile().getStoragePath();
		String dir = "/diance/" + useType + "/";
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));

		String imageId = UUIDGenerator.getUUID();
		fileName = imageId + suffix;

		File dest = new File(path + dir + fileName);
		if (!dest.getParentFile().exists()) { // 判断文件父目录是否存在
			dest.getParentFile().mkdirs();
		}
		try {
			file.transferTo(dest); // 保存文件

			Map<String, String> specImageMap = new HashMap<>();
			specImageMap.put("default", dir + fileName);
			CreateImageSCmd createImageSCmd = new CreateImageSCmd();
			createImageSCmd.setImageId(imageId);
			createImageSCmd.setSuffix(suffix);
			createImageSCmd.setTitle(fileName);
			createImageSCmd.setUrl(dir + fileName);
			createImageSCmd.setSpecImageMapJSON(JSONUtils.toJSONString(specImageMap, false));
			Image image = imageService.createImage(createImageSCmd);
			image.setUrl(iotWispSchoolConfig.getFile().getUrlPrefix() + image.getUrl());
			return ResponseEntity.ok(createSuccessResult(image));
		} catch (IllegalStateException e) {
			log.error(e.getMessage(), e);
			return ResponseEntity.badRequest().body(createFailResult("error", "系统错误", null));
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			return ResponseEntity.badRequest().body(createFailResult("io_error", "系统IO错误", null));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return ResponseEntity.badRequest().body(createFailResult("error", "系统错误", null));
		}

	}

	@PostMapping("/create")
	public ResponseEntity<JSONResultDTO> createImage(@RequestBody CreateImageSCmd cmd) throws BusinessException {

		Image image = imageService.createImage(cmd);
		return ResponseEntity.ok(createSuccessResult(image));
	}
}
